<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  防抖和节流：为了限制函数的执行次数；

  1. 防抖：通过setTimeout的方式，在一定时间间隔内，将多次触发变成一次触发

  2. 节流：减少一段时间的触发频率(1秒内执行一次)

  <hr>
  <input type="text">
  <input type="submit" id="input">


  <script>
    var btn = document.getElementById('input')

    // btn.addEventListener('click', submit, false)
    // btn.addEventListener('click', debounce(submit, 1000), false)
    btn.addEventListener('click', throttle(submit, 1000), false)

    function submit(e) {
      console.log(e);
      console.log(this);
      // console.log(1);
    }

    // 1.防抖 注意点 arguments  this指向
    /* 
    function debounce(fn, time) {
      var t = null
      return function () {
        var firstClick = !t
        if (t) {
          clearTimeout(t)
        }
        if (firstClick) {
          fn.apply(this, arguments)
        }

        t = setTimeout(() => {
          t = null
        }, time)
      }
    }
 */

    // 2.节流
    function throttle(fn, delay) {
      var begin = 0

      return function() {
        var cur = new Date().getTime();
        console.log(cur - begin);
        if (cur - begin > delay) {
          fn.apply(this, arguments);
          begin = cur;
        }
      }
    }
  </script>

</body>

</html>